package top.hkyzf.study.leetcode.graph;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-1-25 14:05
 */
public class 岛屿的最大面积_695 {
    public int maxAreaOfIsland(int[][] grid) {
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1) {
                    int temp = dfs(grid, i, j);
                    result = Math.max(result, temp);
                }
            }
        }
        return result;
    }

    int dfs(int[][] grid, int x, int y) {
        int result = 0;
        if (grid[x][y] == 1) {
            result++;
            grid[x][y] = 0;
            // 上
            if (x-1 >= 0) {
                result = result + dfs(grid, x-1, y);
            }
            // 下
            if (x+1 < grid.length) {
                result = result + dfs(grid, x+1, y);
            }
            // 左
            if (y-1 >=0) {
                result = result + dfs(grid, x, y-1);
            }
            // 右
            if (y+1 < grid[0].length) {
                result = result + dfs(grid, x, y+1);
            }
        }
        return result;
    }

    @Test
    public void testMaxAreaOfIsland() {
        int[][] grid = {
                {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
        };
        System.out.println(maxAreaOfIsland(grid));
    }
}
